﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;

namespace Framework.WebmasterTool.GalleryImages
{
    public partial class Categories : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadCateDDL();
                LoadCateTRV();
                ExpandAllNode();
                LoadCateDetails();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.GalleryImage.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_CateGalleryImage> allCate = entity.udv_CateGalleryImage.ToList();
            List<udv_CateGalleryImage> cateBannerParent = allCate.Where(ca => ca.ParentID == 0).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateDDL(ref List<udv_CateGalleryImage> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_CateGalleryImage> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_CateGalleryImage.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public TreeNode FindNode(string value, TreeNodeCollection nodes)
        {
            foreach (TreeNode n in nodes)
            {
                if (n.Value == value)
                {
                    return n;
                }
                else // search n's child nodes
                {
                    TreeNode nChild = FindNode(value, n.ChildNodes);
                    if (nChild != null)
                        return nChild;
                }
            }
            return null;
        }

        public void ExpandNode(string NootValue)
        {
            TreeNode n = FindNode(NootValue, trvCategories.Nodes);
            while (n != null)
            {
                n.Expand();
                n = n.Parent;
            }
        }

        public void ExpandAllNode()
        {
            List<udv_CateGalleryImage> cateParent = entity.udv_CateGalleryImage.Where(ca => ca.ParentID == 0).ToList();
            foreach (var item in cateParent)
            {
                ExpandNode(item.CateID.ToString());
            }
        }

        public void PopulateCategoriesNode(TreeNode n, List<udv_CateGalleryImage> allCate)
        {
            List<udv_CateGalleryImage> menuChild = allCate.Where(ca => ca.ParentID == int.Parse(n.Value)).ToList();
            if (menuChild.Count == 0)
            {
                return;
            }
            else
            {
                foreach (var item in menuChild)
                {
                    TreeNode treeNodeChild = new TreeNode(item.Title, item.CateID.ToString());
                    treeNodeChild.Collapse();
                    treeNodeChild.NavigateUrl = Globals.ApplicationPath + "WebmasterTool/GalleryImages/Categories.aspx?CateID=" + item.CateID;
                    n.ChildNodes.Add(treeNodeChild);
                    PopulateCategoriesNode(treeNodeChild, allCate);
                }
            }
        }

        public void LoadCateTRV()
        {
            trvCategories.Nodes.Clear();

            List<udv_CateGalleryImage> allCate = entity.udv_CateGalleryImage.ToList();

            var cateParent = allCate.Where(ca => ca.ParentID == 0).ToList();

            if (cateParent.Count != 0)
            {
                foreach (var item in cateParent)
                {
                    TreeNode treeNodeParent = new TreeNode(item.Title, item.CateID.ToString());
                    treeNodeParent.NavigateUrl = Globals.ApplicationPath + "WebmasterTool/GalleryImages/Categories.aspx?CateID=" + item.CateID;
                    trvCategories.Nodes.Add(treeNodeParent);
                    var cateChild = allCate.Where(ca => ca.ParentID == item.CateID);
                    foreach (var subItem in cateChild)
                    {
                        TreeNode treeNodeChild = new TreeNode(subItem.Title, subItem.CateID.ToString());
                        treeNodeChild.NavigateUrl = Globals.ApplicationPath + "WebmasterTool/GalleryImages/Categories.aspx?CateID=" + subItem.CateID;
                        treeNodeParent.ChildNodes.Add(treeNodeChild);
                        PopulateCategoriesNode(treeNodeChild, allCate);
                        trvCategories.ExpandAll();
                    }
                }
            }
        }

        public void LoadCateDetails()
        {
            if (Request.QueryString["CateID"] != null)
            {
                int cateID;
                int.TryParse(Request.QueryString["CateID"], out cateID);
                var cateByID = entity.udv_CateGalleryImage.Where(ca => ca.CateID == cateID).FirstOrDefault();
                if (cateByID != null)
                {
                    ddlCategories.SelectedValue = cateByID.ParentID.ToString();
                    if (cateByID.Remove == false)
                    {
                        ddlCategories.Enabled = false;
                        txtCateName.Enabled = false;
                        btnNew.Visible = true;
                    }
                    else
                    {
                        btnNew.Visible = btnDelete.Visible = true;
                    }
                    txtCateName.Text = cateByID.Title.Trim();
                    txtCateName_en.Text = cateByID.Title_en.Trim();
                    txtDesciption.Text = cateByID.Description;
                    txtDesciption_en.Text = cateByID.Description_en;
                    txtMetaDescription.Text = cateByID.MetaDescription.Trim();
                    txtMetaKeywords.Text = cateByID.MetaKeywords.Trim();
                    txtCateOrder.Text = cateByID.DisplayOrder.ToString();
                    chkIsActive.Checked = cateByID.IsActive.Value;
                    chkCateTop.Checked = cateByID.IsTop.Value;
                    txtPaging.Text = cateByID.PagingSize.ToString();
                    lblAddedDate.Text = String.Format("{0:dd/MM/yyyy}", cateByID.AddedDate);
                    lblAddedBy.Text = cateByID.AddedBy;
                    lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy}", cateByID.UpdatedDate);
                    lblUpdatedBy.Text = cateByID.UpdatedBy;
                }
                else
                {
                    lblMsg.Text = "Danh mục đang chọn không tồn tại";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("Categories.aspx");
        }

        public void AddAllCateDelete(ref List<udv_CateGalleryImage> allCate, int cateParentID, ref List<udv_CateGalleryImage> allCateDelete)
        {
            List<udv_CateGalleryImage> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                allCateDelete.Add(item);
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    AddAllCateDelete(ref allCate, item.CateID, ref allCateDelete);
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["CateID"] != null)
            {
                int cateID;
                int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
                var allCate = entity.udv_CateGalleryImage.ToList();
                var cateDelete = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
                if (cateDelete != null)
                {
                    List<udv_CateGalleryImage> allCateDelete = new List<udv_CateGalleryImage>();
                    AddAllCateDelete(ref allCate, cateDelete.CateID, ref allCateDelete);
                    allCateDelete.Add(cateDelete);
                    allCateDelete = allCateDelete.OrderByDescending(ca => ca.ParentID).ToList();
                    foreach (var item in allCateDelete)
                    {
                        List<udv_GalleryImage> listCateImage = entity.udv_GalleryImage.Where(ic => ic.udv_CateGalleryImage.CateID == item.CateID).ToList();
                        foreach (var subItem in listCateImage)
                        {
                            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + subItem.ImageUrl));
                        }
                        string urlRewriteCategoryOld = Globals.CreateUrlRewriteCategoryGalleryImage(ref entity, item.CateID, true) + DGSFramework.Globals.GetUrlRewriteExtension();
                        Globals.DeleteROR("~/ror.xml", urlRewriteCategoryOld);
                        Globals.DeleteSiteMap("~/sitemap.xml", urlRewriteCategoryOld);
                        Globals.DeleteUrlList("~/urllist.txt", urlRewriteCategoryOld);
                        //create db log
                        CreateDBLog(null, null, TypeAction.Delete, "Xoá danh mục thư viện ảnh: " + item.Title, item.Description, "", "", "",
                        item.IsActive.Value.ToString(), item.IsTop.Value.ToString(), item.MetaKeywords, item.MetaDescription);

                        entity.DeleteObject(item);
                        entity.SaveChanges();
                    }
                    ////clear outputcache
                    //HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
                    Response.Redirect("Categories.aspx");
                }
                else
                {
                    lblMsg.Text = "Danh mục ảnh muốn xoá không tồn tại";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                lblMsg.Text = "Danh mục ảnh muốn xoá không tồn tại";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["CateID"] == null)
            {
                udv_CateGalleryImage cateInsert = new udv_CateGalleryImage();
                cateInsert.AddedDate = DateTime.Now;
                cateInsert.UpdatedDate = DateTime.Now;
                cateInsert.AddedBy = Membership.GetUser().UserName;
                cateInsert.UpdatedBy = Membership.GetUser().UserName;
                cateInsert.Remove = true;
                cateInsert.Title = txtCateName.Text.Trim();
                cateInsert.Title_en = txtCateName_en.Text.Trim();
                cateInsert.Description = txtDesciption.Text;
                cateInsert.Description_en = txtDesciption_en.Text;
                cateInsert.DisplayOrder = int.Parse(txtCateOrder.Text);
                cateInsert.ParentID = int.Parse(ddlCategories.SelectedValue);
                cateInsert.IsActive = chkIsActive.Checked;
                cateInsert.IsTop = chkCateTop.Checked;
                cateInsert.MetaDescription = txtMetaDescription.Text;
                cateInsert.MetaKeywords = txtMetaKeywords.Text;
                cateInsert.PagingSize = int.Parse(txtPaging.Text);
                entity.AddToudv_CateGalleryImage(cateInsert);
                entity.SaveChanges();
                string urlRewriteCategory = Globals.CreateUrlRewriteCategoryGalleryImage(ref entity, cateInsert.CateID, true);
                cateInsert.UrlRewrite = urlRewriteCategory;
                entity.SaveChanges();
                Globals.CreateROR("~/ror.xml", urlRewriteCategory + DGSFramework.Globals.GetUrlRewriteExtension(), cateInsert.Title, cateInsert.MetaDescription);
                Globals.CreateSiteMap("~/sitemap.xml", urlRewriteCategory + DGSFramework.Globals.GetUrlRewriteExtension());
                Globals.CreateUrlList("~/urllist.txt", urlRewriteCategory + DGSFramework.Globals.GetUrlRewriteExtension());

                //create db log
                CreateDBLog(null, null, TypeAction.Insert, "Tạo danh mục hình ảnh: " + cateInsert.Title, cateInsert.Description, "", "", "",
                        cateInsert.IsActive.Value.ToString(), cateInsert.IsTop.Value.ToString(), cateInsert.MetaKeywords, cateInsert.MetaDescription);

                ////clear outputcache
                //HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                //HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                //HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                //HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                //HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                //HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
                Response.Redirect("Categories.aspx");
            }
            else
            {
                int cateID;
                int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
                var cateUpdate = entity.udv_CateGalleryImage.Where(ca => ca.CateID == cateID).FirstOrDefault();
                if (cateUpdate != null)
                {
                    if (ddlCategories.SelectedValue == cateUpdate.CateID.ToString())
                    {
                        lblMsg.Text = "Không cho phép danh mục ảnh muốn cập nhật có danh mục con là chính nó";
                        lblMsg.ForeColor = System.Drawing.Color.Red;
                        return;
                    }
                    if (int.Parse(ddlCategories.SelectedValue) > cateUpdate.CateID)
                    {
                        lblMsg.Text = "Không cho phép chuyển danh mục ảnh cha thành danh mục ảnh con";
                        lblMsg.ForeColor = System.Drawing.Color.Red;
                        return;
                    }
                    string urlRewriteCategoryOld = Globals.CreateUrlRewriteCategoryGalleryImage(ref entity, cateUpdate.CateID, true);
                    string urlRewriteCategoryNew;
                    cateUpdate.UpdatedDate = DateTime.Now;
                    cateUpdate.UpdatedBy = Membership.GetUser().UserName;
                    string oldTitle = cateUpdate.Title;
                    cateUpdate.Title = txtCateName.Text.Trim();
                    cateUpdate.Title_en = txtCateName_en.Text.Trim();
                    cateUpdate.Description = txtDesciption.Text;
                    cateUpdate.Description_en = txtDesciption_en.Text;
                    cateUpdate.DisplayOrder = int.Parse(txtCateOrder.Text);
                    cateUpdate.ParentID = int.Parse(ddlCategories.SelectedValue);
                    cateUpdate.IsActive = chkIsActive.Checked;
                    cateUpdate.IsTop = chkCateTop.Checked;
                    cateUpdate.MetaDescription = txtMetaDescription.Text.Trim();
                    cateUpdate.MetaKeywords = txtMetaKeywords.Text.Trim();
                    cateUpdate.PagingSize = int.Parse(txtPaging.Text);
                    entity.SaveChanges();
                    urlRewriteCategoryNew = Globals.CreateUrlRewriteCategoryGalleryImage(ref entity, cateUpdate.CateID, true);
                    cateUpdate.UrlRewrite = urlRewriteCategoryNew;
                    entity.SaveChanges();
                    Globals.UpdateROR("~/ror.xml", urlRewriteCategoryOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteCategoryNew + DGSFramework.Globals.GetUrlRewriteExtension(), cateUpdate.Title, cateUpdate.MetaDescription);
                    Globals.UpdateSiteMap("~/sitemap.xml", urlRewriteCategoryOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteCategoryNew + DGSFramework.Globals.GetUrlRewriteExtension());
                    Globals.UpdateUrlList("~/urllist.txt", urlRewriteCategoryOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteCategoryNew + DGSFramework.Globals.GetUrlRewriteExtension());

                    //create db log
                    CreateDBLog(null, null, TypeAction.Update, "Cập nhật danh mục hình ảnh: " + oldTitle + " - " + cateUpdate.Title, cateUpdate.Description, "", "", "",
                            cateUpdate.IsActive.Value.ToString(), cateUpdate.IsTop.Value.ToString(), cateUpdate.MetaKeywords, cateUpdate.MetaDescription);
                    
                    ////clear outputcache
                    //HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
                    //HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
                    Response.Redirect("Categories.aspx");
                }
                else
                {
                    lblMsg.Text = "Danh mục muốn cập nhật không tồn tại";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void btnGalleryImage_Click(object sender, EventArgs e)
        {
            Response.Redirect("GalleryImages.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}